<template>
    <view class="container">
        <form @submit.prevent="handleRegister">
            <view class="input-group">
                <text>邮箱:</text>
                <input type="email" v-model="email" placeholder="请输入邮箱" />
            </view>
            <view class="input-group">
                <button @click.prevent="sendCode" :disabled="codeSent">发送验证码</button>
            </view>
            <view class="input-group">
                <text>验证码:</text>
                <input type="number" v-model="code" placeholder="请输入验证码" />
            </view>
            <view class="input-group">
                <text>密码:</text>
                <input type="password" v-model="password" placeholder="请输入密码" />
            </view>
            <view class="input-group">
                <text>确认密码:</text>
                <input type="password" v-model="confirmPassword" placeholder="请确认密码" />
            </view>
            <button type="submit">注册</button>
        </form>
    </view>
</template>

<script>
export default {
    data() {
        return {
            email: '',
            password: '',
            confirmPassword: '',
            code: '',
            codeSent: false, // 控制按钮状态
            timer: null,
            countdown: 60 // 倒计时
        };
    },
    methods: {
        async sendCode() {
            if (!this.email) {
                uni.showToast({
                    title: '请输入邮箱',
                    icon: 'none'
                });
                return;
            }

            // 校验邮箱格式
            const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
            if (!emailRegex.test(this.email)) {
                uni.showToast({
                    title: '邮箱格式不正确',
                    icon: 'none'
                });
                return;
            }
            // 发送验证码请求
            try {
                const res = await uni.request({
                    url: 'http://114.132.162.113:8000/api/email/code/',
                    method: 'POST',
                    header: {
                        'Content-Type': 'application/json'
                    },
                    data: {
                        email: this.email
                    }
                });

                if (res[1].statusCode === 200) {
                    uni.showToast({
                        title: '验证码发送成功',
                        icon: 'success'
                    });
                    this.codeSent = true;
                    this.startCountdown(); // 开始倒计时
                } else {
                    uni.showToast({
                        title: res.data.message || '验证码发送失败',
                        icon: 'none'
                    });
                }
            } catch (error) {
                uni.showToast({
                    title: '请求失败',
                    icon: 'none'
                });
                console.error(error);
            }
        },
        startCountdown() {
            this.timer = setInterval(() => {
                if (this.countdown > 0) {
                    this.countdown--;
                } else {
                    clearInterval(this.timer);
                    this.codeSent = false;
                    this.countdown = 60; // 重置倒计时
                }
            }, 1000);
        },
        async handleRegister() {
            // 校验密码是否一致
            if (this.password !== this.confirmPassword) {
                uni.showToast({
                    title: '两次输入的密码不一致',
                    icon: 'none'
                });
                return;
            }

            // 校验密码是否符合标准
            const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d).{6,18}$/;
            if (!passwordRegex.test(this.password)) {
                uni.showToast({
                    title: '密码必须包含字母与数字，长度为6-18位',
                    icon: 'none'
                });
                return;
            }

            // 获取当前IP的城市
            let city = 'unknown';
            try {
                const [error, res] = await uni.request({
                    url: 'http://ip-api.com/json',
                    method: 'GET'
                });
                if (!error && res.statusCode === 200) {
                    city = res.data.city;
                }
            } catch (error) {
                console.error('获取城市信息失败', error);
            }

            // 发送注册请求
            try {
                const res = await uni.request({
                    url: 'http://114.132.162.113:8000/api/uesr/register/',
                    method: 'POST',
                    header: {
                        'Content-Type': 'application/json'
                    },
                    data: {
                        email: this.email,
                        password: this.password,
                        code: this.code,
                        city: city
                    }
                });

                if (res[1].statusCode === 200) {
                    uni.showToast({
                        title: '注册成功',
                        icon: 'success'
                    });
                    // 设置cookie
                    const cookies = res[1].header['Set-Cookie'];
                    if (cookies) {
                        uni.setStorageSync('cookies', cookies);
                    }
                } else {
                    uni.showToast({
                        title: res.data.message || '注册失败',
                        icon: 'none'
                    });
                }
            } catch (error) {
                uni.showToast({
                    title: '请求失败',
                    icon: 'none'
                });
                console.error(error);
            }
        }
    },
    beforeDestroy() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    }
};
</script>

<style>
.container {
    padding: 20px;
}

.input-group {
    margin-bottom: 15px;
}

input {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
}

button {
    width: 100%;
    padding: 10px;
    background-color: #007aff;
    color: white;
    border: none;
    border-radius: 5px;
}

button[disabled] {
    background-color: #ccc;
}
</style>
